﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Const;
using UnityEngine;
using Entitas;
using Services;

public class FallSystem : ReactiveSystem<GameEntity>
{
    private Contexts _contexts;
    public FallSystem(Contexts context) : base(context.game)
    {
        _contexts = context;
    }

    protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context)
    {
        return context.CreateCollector(GameMatcher.ComponentsItem.Removed());
    }

    protected override bool Filter(GameEntity entity)
    {
        return !entity.isComponentsItem;
    }

    protected override void Execute(List<GameEntity> entities)
    {
        var gameBoard = _contexts.game.componentsGameBoardComponents;
        for (int column = 0; column < gameBoard.columns; column++)
        {
            for (int row = 0; row < gameBoard.raws; row++)
            {
                var pos=new customData(column,row);
                var movable = _contexts.game.GetEntitiesWithComponentsItemIndex(pos)
                    .Where(e => e.isComponentsMovable).ToArray();

                foreach (GameEntity entity in movable)
                {
                    MoveDown(entity);
                }
            }
        }
    }

    private void MoveDown(GameEntity entity)
    {
        var nextRow = GetEmptyItemService
            .Instance
            .GetNextEmptyRow(entity.componentsItemIndex.index);
        if (nextRow < entity.componentsItemIndex.index.y)
        {
            entity.ReplaceComponentsFallState(fallState.FALL);
            entity.ReplaceComponentsItemIndex(new customData(entity.componentsItemIndex.index.x,nextRow));
        }
        
        
    }
}
